//
//  SimpleVideoPlayer.m
//  SimpleVideoPlayer
//
//  Created by Handymood on 11-5-21.
//  Copyright 2011 __Hanydmood__. All rights reserved.
//

#import "SimpleVideoPlayer.h"

@implementation SimpleVideoPlayer

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) 
    {
        // Initialization code
        isInBuffer = false;
        bufferTime = 5.0f;
    }
    return self;
}

-(void)initVideoPlayer:(NSString *)inVideoPath
                  videoSize:(CGSize )inSize
                    autoPlay:(BOOL) inAutoPlay
                       isLoop:(BOOL) inLoop
                 ratioMode:(int) inRatioMode
               playerStyle:(int) inPlayerStyle
  slideshowAutoPlay:(BOOL) isSlideshowAutoPlay
            slideBgmOn:(BOOL) isSlideBgmOn
                     inFade:(int) isFade
{
    type = @"VIDEO_PLAYER";
    if(inVideoPath == Nil || [inVideoPath length] <=4)
    {
        return;
    }
 
    //get slideshow autoplay status
    slideshowAutoPlay = isSlideshowAutoPlay;
    
    //init the frame,for the interactive puspose
    self.frame = CGRectMake(self.frame.origin.x,self.frame.origin.y,inSize.width,inSize.height);
    
    isInBuffer = false;
    
    NSString *fileNamePrefix = [inVideoPath  substringWithRange:NSMakeRange(0, [inVideoPath  length] - 4)];
    NSString *fileNameSuffix = [inVideoPath  substringWithRange:NSMakeRange([inVideoPath length]-3,3)];
    
    //init meida player : download from local
    NSString *videoPath;
    NSURL *videoURL;

    //add the loading indication for web stream video & local video
    activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activityIndicator.frame = CGRectMake(0.0, 0.0, 40.0, 40.0);
    activityIndicator.center = self.center;
    
    if([inVideoPath length] > 11)
    {
        NSString *httpSuffix = [inVideoPath substringWithRange:NSMakeRange(0,7)];

        if([[httpSuffix lowercaseString] isEqualToString:@"http://"])
        {
            videoURL = [NSURL URLWithString:inVideoPath];

            //add the loading detect,for web loading
            float kTimerInternal = 0.2f;
                    loadDetectTimer = [NSTimer scheduledTimerWithTimeInterval: kTimerInternal target:self selector:@selector(webLoadingDetect) userInfo:nil repeats:YES];
        }
        else
        {
            videoPath = [[NSBundle mainBundle] pathForResource:fileNamePrefix ofType:fileNameSuffix];
            
            if(!videoPath)
                return;
            
            videoURL= [NSURL fileURLWithPath:videoPath]; 
        }
    }
    else
    {
        videoPath = [[NSBundle mainBundle] pathForResource:fileNamePrefix ofType:fileNameSuffix];
        
        if(!videoPath)
            return;
        
        videoURL= [NSURL fileURLWithPath:videoPath];
    }

    mediaPlayer = [[ MPMoviePlayerController alloc] initWithContentURL:videoURL];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(playbackFinished:)
                                                 name:@"MPMoviePlayerPlaybackDidFinishNotification" 
                                               object:mediaPlayer];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(playbackStateChanged:)
                                                 name:@"MPMoviePlayerPlaybackStateDidChangeNotification" 
                                               object:mediaPlayer];
    
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(playLoadStateChanged:) 
                                                 name:@"MPMoviePlayerLoadStateDidChangeNotification"
                                               object:mediaPlayer];
    
    mediaPlayer.view.backgroundColor = [UIColor clearColor];
    
    //set ratio mode
    if (inRatioMode == 1) 
    {
        mediaPlayer.scalingMode = MPMovieScalingModeAspectFit;
    }
    else
    {
        mediaPlayer.scalingMode = MPMovieScalingModeFill;
    }
    
    mediaPlayer.view.frame = CGRectMake(0, 0, inSize.width,inSize.height);

    //set player controller mode
    if (inPlayerStyle == 0) 
    {
        mediaPlayer.controlStyle = MPMovieControlStyleNone;
    }
    else if (inPlayerStyle == 1) 
    {
        mediaPlayer.controlStyle = MPMovieControlStyleEmbedded;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"tool_bar_hide" object:self];
    }
    else if (inPlayerStyle == 2) 
    {
        mediaPlayer.controlStyle = MPMovieControlStyleFullscreen;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"tool_bar_hide" object:self];
    }
    else
    {
        mediaPlayer.controlStyle = MPMovieControlStyleNone;
    }

    mediaPlayer.shouldAutoplay =  inAutoPlay;
    
    //init the background interactive hit
    backgroundBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backgroundBtn.backgroundColor = [UIColor clearColor];
    backgroundBtn.frame = CGRectMake(0, 0, inSize.width, inSize.height);
    [backgroundBtn addTarget:self action:@selector(pauseBtnMouseDownProc:) forControlEvents:UIControlEventTouchDown];
    
    //init the play btn
    playBtn = [ImageUIButton buttonWithType:UIButtonTypeCustom];
    [playBtn addButtonFace:@"playBtn" normalImgSuffix:@"png" downImgPrefix:@"playBtn" downImgSuffix:@"png"];
    [playBtn setXY: inSize.width/2-playBtn.frame.size.width/2 offy:inSize.height/2-playBtn.frame.size.height/2];
    [playBtn addTarget:self action:@selector(playBtnMouseDownProc:) forControlEvents:UIControlEventTouchDown];
    
    if(inAutoPlay)
    {
        playBtn.hidden = TRUE;
        [mediaPlayer play];
    }
    
    isLoop = inLoop;
    
    [self addSubview:mediaPlayer.view];
    
    if(activityIndicator)
    {
        [self addSubview: activityIndicator];
        [activityIndicator startAnimating];
    }
    
    [self addSubview:backgroundBtn];
    [self addSubview:playBtn]; 
    
    if (inPlayerStyle >= 1 && inPlayerStyle <= 2) 
    {
        playBtn.hidden = TRUE;
        backgroundBtn.hidden = TRUE;
    }
    
    fade = isFade;
}

-(void) playBtnMouseDownProc:(id)sender
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"tool_bar_hide" object:self];
    [self resumeVideoFunc];
    playBtn.hidden = TRUE;
}

-(void) pauseBtnMouseDownProc:(id)sender
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"tool_bar_show" object:self];
    [self pauseVideoFunc];
    playBtn.hidden = FALSE;
}

-(void) playbackFinished:(NSNotification*) notification
{
    if (fade) 
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"shift_to_main_page" object:self];
        //self.hidden = TRUE;
        return;
    }
    
    if(mediaPlayer && playBtn)
    {
        if(isLoop)
            [mediaPlayer play];
        else
        {
            if (mediaPlayer.controlStyle == MPMovieControlStyleNone)
            {
                playBtn.hidden =  FALSE;
            }
        }
    }
}

-(void) playLoadStateChanged:(NSNotification*) notification
{
    if(!mediaPlayer)
        return;
    
    switch ([mediaPlayer loadState]) 
    {
        case MPMovieLoadStateUnknown:
            //NSLog(@"playstatus unknown");
            isInBuffer = false;
            break;
        case MPMovieLoadStatePlayable:
            if(activityIndicator)
            {
                [activityIndicator stopAnimating];
            }
            //NSLog(@"playable");
            isInBuffer = false;
            break;
        case 3://MPMovieLoadStatePlaythroughOK:
            if(activityIndicator)
            {
                [activityIndicator stopAnimating];
            }
            isInBuffer = false;
            //NSLog(@"playthroughok");
            break;
        case 5://MPMovieLoadStateStalled:
            if(activityIndicator)
            {
                [activityIndicator startAnimating];
            }
            //NSLog(@"playstatusstalled");
            isInBuffer = true;
            break;
        default:
            isInBuffer = false;
            //NSLog(@"default:%d",[mediaPlayer loadState]);
            break;
    }
}

-(void) playbackStateChanged:(NSNotification*) notification
{
        if( mediaPlayer.playbackState == MPMoviePlaybackStateStopped || 
            mediaPlayer.playbackState == MPMoviePlaybackStatePaused)
        {
            if(mediaPlayer.controlStyle == MPMovieControlStyleEmbedded || 
               mediaPlayer.controlStyle == MPMovieControlStyleFullscreen)
            {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"tool_bar_hide" object:self];
            }
        }
        else if( mediaPlayer.playbackState == MPMoviePlaybackStatePlaying)
        {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"tool_bar_hide" object:self];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"manually_pause_slideshow" object:self];
        }    
}

-(void) pauseVideoFunc
{
    [mediaPlayer pause];
}

-(void)resumeVideoFunc
{
    [mediaPlayer play];
}

-(void) webLoadingDetect
{
    if(mediaPlayer)
    {
        if(isInBuffer && [mediaPlayer playableDuration]-[mediaPlayer currentPlaybackTime]>bufferTime)
        {
            [mediaPlayer play];    
            isInBuffer = false;
        }
    }
}

-(void)setXY:(CGFloat) inx 
        offy:(CGFloat) iny
{
    self.frame = CGRectMake(inx, iny, self.frame.size.width, self.frame.size.height);
}

-(void)pause
{
    [self pauseBtnMouseDownProc:Nil];
}

-(void) layoutAdjustWithOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    CGRect screen_rect = [[UIScreen mainScreen] bounds];
    CGFloat screen_width = screen_rect.size.width;
    CGFloat screen_height = screen_rect.size.height;
    
    if(interfaceOrientation == UIInterfaceOrientationPortrait || 
       interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
    {
        self.frame = CGRectMake(0, 0, screen_width, screen_height);
        [playBtn setXY: screen_width/2-playBtn.frame.size.width/2 offy:screen_height/2-playBtn.frame.size.height/2];
        mediaPlayer.view.frame = self.frame;
    }
    else if(interfaceOrientation == UIInterfaceOrientationLandscapeRight || 
            interfaceOrientation == UIInterfaceOrientationLandscapeLeft)
    {
        self.frame = CGRectMake(0, 0,screen_height, screen_width);
        [playBtn setXY: screen_height/2-playBtn.frame.size.width/2 offy:screen_width/2-playBtn.frame.size.height/2];
        mediaPlayer.view.frame = self.frame;
    }
}

-(BOOL) mediaOnPlaying
{
    if (mediaPlayer != Nil) 
    {
        if (mediaPlayer.playbackState == MPMoviePlaybackStatePlaying) 
        {
            return TRUE;
        }
        else
        {
            return FALSE;
        }
    }
    else
    {
        return FALSE;
    }
}

-(void)reset
{
    if(mediaPlayer)
    {
        isLoop = false;

        [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                     name:@"MPMoviePlayerLoadStateDidChangeNotification"
                                                   object:mediaPlayer];
        
        [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                        name:@"MPMoviePlayerPlaybackStateDidChangeNotification" 
                                                    object:mediaPlayer];
        
        [[NSNotificationCenter defaultCenter] removeObserver:self
                                                        name:@"MPMoviePlayerPlaybackDidFinishNotification" 
                                                      object:mediaPlayer];     
     
        [mediaPlayer pause];
        mediaPlayer.initialPlaybackTime = -1;
        [mediaPlayer stop];
        mediaPlayer.initialPlaybackTime = -1;
        
        [mediaPlayer.view removeFromSuperview];
        [mediaPlayer release];
    }
    
    if(loadDetectTimer)
    {
        [loadDetectTimer invalidate];
        loadDetectTimer = Nil;
    }
    
    if(backgroundBtn)
    {
        [backgroundBtn removeTarget:self action:@selector(pauseBtnMouseDownProc:) forControlEvents:UIControlEventTouchDown];
        [backgroundBtn removeFromSuperview];
    }
    
    if(playBtn)
    {
        [playBtn removeTarget:self action:@selector(pauseBtnMouseDownProc:) forControlEvents:UIControlEventTouchDown];
        [playBtn removeFromSuperview]; 
    }
    
    if(activityIndicator)
    {
        [activityIndicator release];
        [activityIndicator removeFromSuperview];
    }
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

- (void)dealloc
{
    [super dealloc];
}

@end
